<?php
/**
 * Descript:
 * User: lufeng501206@gmail.com
 * Date: 2017/3/12 16:35
 */

namespace App\Repositories;


use App\Models\AdminUser;
use App\Models\Home\Orders;
use App\Models\Home\User;
use App\Models\LoginLogs;
use App\Models\MessagesReader;
use App\Models\MessagesTemplate;

class UsersRepos
{
    private $tasksRepos;

    public function __construct(TasksRepos $tasksRepos)
    {
        $this->tasksRepos = $tasksRepos;
    }

    /**
     * 获取登录用户的ID
     */
    public function getLoginUserId()
    {
        $loginAccount = session('login_user');
        $userModel = User::select('*');
        $userModel = $userModel->where('account', $loginAccount);
//        $userModel = $userModel->where(function ($query) use ($loginAccount) {
//            $query->where('account',$loginAccount)
//                ->orWhere('mobile',$loginAccount);
//        });
        $userRes = $userModel->first();
        return $userRes['id'];
    }

    public function getAdminUserId($account)
    {
        $userRes = AdminUser::where('username', $account)->first()->toArray();
        return $userRes['id'];
    }

    /**
     * 获取登录用户的信息
     */
    public function getLoginUserInfo()
    {
        $loginMobile = session('login_user');
        $userRes = User::whereAccount($loginMobile)->first();
        return $userRes;
    }

    /**
     * 获取用户信息
     * @param $id
     * @return mixed
     */
    public function getUserInfo($id)
    {
        $info = User::findOrFail($id)->toArray();
        return $info;
    }

    public function getUserInfoByAccount($account) {
        $info = User::where('account',$account)->first()->toArray();
        return $info;
    }

    /**
     * 获取用户信息
     * @param $id
     * @return mixed
     */
    public function getUserDetailInfo($id)
    {
        $info = User::findOrFail($id)->toArray();
        $info['login_log'] = $this->getUserLoginLogs($info['account'], true);
        $info['transform_cash'] = $this->tasksRepos->getUserMoney($id, 2);
        $info['transform_cash'] = number_format($info['transform_cash'],2);
        $info['total_earnings'] = number_format($info['transform_cash'] + $info['balance'],2);
        return $info;
    }

    /**
     * 获取用户列表
     * @param array $conditions
     * @return array
     */
    public function getUsersLists($conditions = [], $returnLists = true)
    {
        $userModel = User::select('*');
        if (!empty($conditions['id'])) {
            $userModel = $userModel->where('id', $conditions['id'])->limit(1);
        }
        if (!empty($conditions['state'])) {
            $userModel = $userModel->where('state', $conditions['state']);
        }
        if (!empty($conditions['name'])) {
            $userModel = $userModel->where('name', 'like', '%' . $conditions['name'] . '%');
        }

        if (!$returnLists) {
            $total = $userModel->count();
        }

        if (!empty($conditions['start'])) {
            $userModel = $userModel->offset($conditions['start']);
        }
        if (!empty($conditions['limit'])) {
            $userModel = $userModel->limit($conditions['limit']);
        }
        $lists = $userModel->get()->toArray();
        if (!empty($lists)) {
            foreach ($lists as $key => &$value) {
                $value['client_ip'] = $this->getUserLastLoginIp($value['account']);
                $value['transform_cash'] = $this->tasksRepos->getUserMoney($value['id'], 2);
                $value['transform_cash'] = number_format($value['transform_cash'],2);
                $value['total_earnings'] = number_format($value['transform_cash'] + $value['balance'],2);
            }
        }
        if ($returnLists) {
            return $lists;
        } else {
            $data['total'] = $total;
            $data['lists'] = $lists;
            return $data;
        }
    }

    /**
     * 获取用户最后一次登录ip
     * @param $mobile
     * @return string
     */
    public function getUserLastLoginIp($mobile)
    {
        $res = LoginLogs::where('mobile', $mobile)->orderBy('id', 'desc')->first();
        if (!empty($res)) {
            return $res['client_ip'];
        } else {
            return '';
        }
    }

    /**
     * 获取好友列表
     * @param $mobile
     * @return mixed
     */
    public function getFriendLists($account)
    {
        $lists = User::where('recommend_user', $account)->orderBy('created_at', 'asc')->get()->toArray();
        // 获取好友的任务提成
        if (!empty($lists)) {
            foreach ($lists as $k => &$v) {
                $v['total_reward_earnings'] = $this->getRewardEarnings($v['id']);
            }
        }
        return $lists;
    }

    /**
     * 获取好友列表
     *
     * @param $account
     * @return mixed
     */
    public function getRecommendUserLists($account)
    {
        $lists = User::where('recommend_user', $account)->orderBy('created_at', 'asc')->get()->toArray();
        return $lists;
    }

    /**
     * 获取好友用户的任务提成
     * @param $userId
     * @return int
     */
    public function getRewardEarnings($userId)
    {
        $orderTaskModel = Orders::leftJoin('tasks', 'tasks.id', '=', 'orders.task_id');
        $orderTaskModel = $orderTaskModel->where('orders.user_id', $userId);
        $orderTaskModel = $orderTaskModel->where('orders.state', 4);
        $totalMoney = $orderTaskModel->sum('tasks.money');
        if (!empty($totalMoney)) {
            return number_format($totalMoney * 0.2, 2, '.', '');
        } else {
            return 0;
        }
    }

    /**
     * 获取用户登录日志
     * @param $mobile
     * @return mixed
     */
    public function getUserLoginLogs($mobile, $resultLast = false)
    {
        $lists = LoginLogs::where('mobile', $mobile)->get()->toArray();
        if ($resultLast) {
            if (!empty($lists) && is_array($lists)) {
                return end($lists);
            } else {
                return [];
            }
        } else {
            return $lists;
        }
    }

    /**
     * 新增模板
     * @param $title
     * @param $messages
     * @param int $type
     * @return bool
     */
    public function createMessagesTemplate($title, $messages, $type = 1)
    {
        $messagesModel = new MessagesTemplate();
        $messagesModel->title = $title;
        $messagesModel->messages = $messages;
        $messagesModel->type = $type;
        $res = $messagesModel->save();
        if ($res) {
            return $messagesModel->id;
        } else {
            return false;
        }
    }

    /**
     * @param $templateId
     * @param $userlists
     * @return bool
     */
    public function createMessagesReader($templateId, $userlists)
    {
        if (!empty($userlists) && is_array($userlists)) {
            $flag = true;
            foreach ($userlists as $value) {
                $readerModel = new MessagesReader();
                $readerModel->message_id = $templateId;
                $readerModel->user_id = $value;
                $res = $readerModel->save();
                if (empty($res)) {
                    $flag = false;
                    break;
                }
            }
        }
        if (!empty($flag)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 触发消息
     * @param $title
     * @param $data
     * @return bool
     */
    public function triggerMessage($userid, $title, $data)
    {
        $msgModel = MessagesTemplate::where('title', $title)->where('type', 2)->first()->toArray();
        $msgTemplate = $msgModel['messages'];
        if (!empty($data)) {
            foreach ($data as $key => $value) {
                $msgTemplate = str_replace($key, $value, $msgTemplate);
            }
            $templateId = $this->createMessagesTemplate($title, $msgTemplate, 3);
            $readerModel = new MessagesReader();
            $readerModel->message_id = $templateId;
            $readerModel->user_id = $userid;
            $res = $readerModel->save();
            if (!empty($res)) {
                return true;
            } else {
                \Log::error($title . '消息触发失败');
            }
        }
        return true;
    }

    /**
     * 获取消息列表数据
     * @param $userId
     * @param array $conditions
     * @return mixed
     */
    public function getMessagesLists($userId, $conditions = [])
    {
        $messagesModel = MessagesTemplate::select('*', 'messages_template.id as id');
        $messagesModel = $messagesModel->leftJoin('messages_reader', 'messages_reader.message_id', '=', 'messages_template.id');
        $messagesModel = $messagesModel->where('user_id', $userId);
        if (!empty($conditions['id'])) {
            $messagesModel = $messagesModel->where('messages_template.id', $conditions['id']);
            $lists = $messagesModel->first()->toArray();
            return $lists;
        }
        if (!empty($conditions['read_state'])) {
            $messagesModel = $messagesModel->where('read_state', $conditions['read_state']);
        } else {
            $messagesModel = $messagesModel->whereIn('read_state', [1, 2]);
        }
        if (!empty($conditions['total'])) {
            $total = $messagesModel->count();
            return $total;
        }
        $lists = $messagesModel->orderBy('messages_reader.id', 'desc')->get()->toArray();
        return $lists;
    }
}